<template>
  <span>
    <el-button type="success" size="medium" @click="handleOpen">导入</el-button>

    <div style="display: none">
      <ele-import
        :fields="fields"
        :filepath="filepath"
        :request-fn="requestFn"
        :extra-data="extraData"
        :rules="rules"
        :tips="tips"
        :title="title"
        :visible.sync="visible"
        @close="handleCloseImport"
        @finish="handleFinishImport"
      />
    </div>
  </span>
</template>

<script>
import EleImport from '@/utils/myImport.vue'
export default {
  name: 'App',
  components: {
    EleImport
  },
  data() {
    return {
      // 弹窗的标题
      title: '导入模板',
      // 提示信息
      tips: ['请按照模板上传，电话、金额不能为空，否则会导致导入不成功;日期必须使用文本格式;如上传数据出现未设置电话账号，会导致取消上传，请先设置账号'],
      // 假如数据库中是`name`字段, 而Excel模板列是`名字`, 就需要写成 name: '名字'
      // ele-import 内部会抛弃非定义在fields里的列
      fields: {
        username: '电话',
        amount: '汇款金额'
      },
      rules: {
        username: { type: 'number', required: true, message: '电话不能为空' },
        amount: [
          { type: 'number', message: '汇款金额需为数字类型' },
          { required: true, message: '汇款金额不能为空' }
        ]
      },
      filepath: `http://pub.nightkper.com/demo.xlsx`,
      // 控制弹窗, 和dialog的visible一样
      // https://element.eleme.cn/#/zh-CN/component/dialog
      visible: false,
      // 额外选择信息
      extraData: {
        choose: null,
        title: '发放方式:',
        options: [{ value: 1, label: '余额' }, { value: 2, label: '银行卡' }]
      }
    }
  },
  mounted() {
    console.log('route', window.location.host)
  },
  methods: {
    // requestFn函数会被注入请求的数据
    // 需要返回一个Promise对象
    async requestFn(data) {
      console.log(this.extraData)
      if (!this.extraData.choose) {
        return Promise.reject({ 0: { '出错了': '请选择发放方式!' }})
      }
      let users = []
      try {
        let filter = 'entity.getUsername() in ['
        for (var i in data) {
          if (Number(i) === data.length - 1) {
            filter = filter + data[i].username + ']'
          } else {
            filter = filter + data[i].username + ','
          }
        }
        console.log('filter', filter)
        const res = await this.axios.get(`/officer/users`, {
          params: {
            '@filter': filter,
            'limit': 100000000
          }
        })
        users = res.data
      } catch (err) {
        this.$message.error('获取账号数据失败')
        return Promise.reject({ 0: { '出错了': '导入错误，请重试' }})
      }
      if (users.length === 0) {
        this.$message.warning('列表一个账号信息都没有!')
      }
      const sendData = []
      const failData = []
      const withdrawData = []
      for (var j in data) {
        const check = users.find(g => g.username === data[j].username.toString())
        if (check) {
          sendData.push({ to: check.id, amount: data[j].amount, type: 'upload', comment: '导入发放' })
          withdrawData.push({ user: check.id, amount: data[j].amount })
        } else {
          failData.push(data[j].username)
        }
      }
      if (failData.length > 0) {
        return Promise.reject({ 0: { '出错了': `电话${failData.toString()}未建立用户信息，请重试` }})
      }

      try {
        await this.axios.post(`/officer/transactions/send`, sendData)
      } catch (err) {
        return Promise.reject({ 0: { '出错了': '转账错误！' }})
      }

      if (this.extraData.choose > 1) {
        try {
          await this.axios.post(`/officer/withdraws`, withdrawData, { params: { '@partial': true }})
        } catch (err) {
          this.$message.warning('转账成功，提现失败!')
        }
      }

      return Promise.resolve()
    },
    handleCloseImport() {
      console.log('组件关闭了~')
    },
    handleFinishImport() {
      console.log('导入完毕了~')
      location.reload()
    },
    handleOpen() {
      this.visible = true
    }
  }
}
</script>

<style scoped>

</style>
